<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ include file="/pages/common/taglibs.jsp"%>
<%
	String dynamicDomain = DomainUtils.getDynamicDomain();
	String message = request.getParameter(FrameworkConstants.MESSAGE);
	if (message == null) {
		message = String.valueOf(request
				.getAttribute(FrameworkConstants.MESSAGE));
	}
	if (message == null || "null".equals(message)) {
		message = "";
	}else{
		request.setAttribute(FrameworkConstants.MESSAGE,message);
	}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@page import="com.mvc.framework.FrameworkConstants"%>
<%@page import="com.mvc.framework.util.DomainUtils"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Language" content="zh-cn" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
<meta http-equiv="Cache-Control" content="no-cache" />
<jdf:themeFile file="common.css" />
<jdf:themeFile file="zTree.css" />
<jdf:themeFile file="jquery-ui-1.8.2.custom.css" />
<jdf:themeFile file="jquery-1.7.2.min.js" />
<jdf:themeFile file="jquery.corner.js" />
<jdf:themeFile file="common.js" />
<jdf:themeFile file="jquery.hotkeys.js" />
<jdf:themeFile file="jquery.ztree.all-3.3.min.js" />
<jdf:themeFile file="jquery-ui-1.8.17.custom.min.js" />
<script type="text/javascript">
        var setting = {
            async: {
                enable: true,
                url:"<%=dynamicDomain%>/dict/getChildren?ajax=1",
                autoParam:["id", "name=n", "level=lv"]
            },
            view: {
            	expandSpeed:"",
                addHoverDom: addHoverDom,
                removeHoverDom: removeHoverDom,
                selectedMulti: false
            },
            edit: {
                enable: true,
                editNameSelectAll: true,
                showRenameBtn: false,
                showRemoveBtn:false
            },
            data: {
                simpleData: {
                    enable: true,
                    pIdKey: "parentId"
                }
            }
        };

        function filter(treeId, parentNode, childNodes) {
            if (!childNodes) return null;
            for (var i=0, l=childNodes.length; i<l; i++) {
                childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
            }
            return childNodes;
        }
        function beforeRemove(treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("topicTree");
            zTree.selectNode(treeNode);
            return confirm("确认删除 节点 -- " + treeNode.name + " 吗？");
        }       
        function beforeRename(treeId, treeNode, newName) {
            if (newName.length == 0) {
                alert("节点名称不能为空.");
                return false;
            }
            return true;
        }

        var newCount = 1;
        function addHoverDom(treeId, treeNode) {
            var sObj = $("#" + treeNode.tId + "_span");
            if ($("#addBtn_"+treeNode.id).length>0) return;
            var addStr = "<span class='button add' id='addBtn_" + treeNode.id + "' title='add node' onfocus='this.blur();'></span>";
            addStr += "<span class='button edit' id='editBtn_" + treeNode.id + "' title='edit node' onfocus='this.blur();'></span>";
            sObj.append(addStr);
            var btn = $("#addBtn_"+treeNode.id);
            if (btn) btn.bind("click", function(){
            	currentObjectId = "";
                $("#dict_id").val("");
                $("#dict_objectId").val("");
                $("#dict_parentId").val(treeNode.id);
                $("#dict_name").val("");
                $("#dict_status").val("");
                $("#dict_sortId").val(1);
                $("#dict_remark").val("");
                $("#dict_dictionaryId").val("");
                $("#dict_type").val("2");
                $("#dict_value").val("");
                currentNode = treeNode;
                $("#addArea").dialog({height: 350,width:660,resizable:false});
            	
            });
            
            var btn2 = $("#editBtn_"+treeNode.id);
            if (btn2) btn2.bind("click", function(){
                currentObjectId = treeNode.id;
                 $("#dict_objectId").val(currentObjectId);
                $("#dict_parentId").val(treeNode.parentId);
                $("#dict_id").val(treeNode.primaryKey);
                currentNode = treeNode;
                $("#dict_name").val(treeNode.realName);
                $("#dict_dictionaryId").val(treeNode.dictionaryId);
                $("#dict_value").val(treeNode.value);
                $("#dict_status").val(treeNode.status?1:0);
                $("#dict_remark").val(treeNode.remark);
                $("#dict_sortId").val(treeNode.sortId);
                $("#dict_type").val(treeNode.type); 
                $("#addArea").dialog({height: 350,width:660,resizable:false});
                
            });
            
        };
        
        function removeHoverDom(treeId, treeNode) {
            $("#addBtn_"+treeNode.id).unbind().remove();
            $("#editBtn_"+treeNode.id).unbind().remove();
        };
        
        var root = ${root};
        $(document).ready(function(){
            $.fn.zTree.init($("#topicTree"), setting, root);
        });
        
        var count=0; 
        var lastName; 
        function doSearch(){ 
        	if(count==0){ 
       			lastName=document.getElementById("search_str").value; 
        	} 
        	if(lastName!=document.getElementById("search_str").value){ 
       			count=0; 
        		lastName=document.getElementById("search_str").value; 
        	} 
        	var treeObj = $.fn.zTree.getZTreeObj("topicTree"); 
	        //通过名称模糊搜索，也可通过Id查找 
	        var nodes =   treeObj.transformToArray(treeObj.getNodesByParamFuzzy("name", lastName, null)); 
            for(i = count; i < nodes.length; i++) { 
        		count++; 
        		if(count>=nodes.length){ 
        			count=0; 
        		} 
        		if(nodes[i].name.indexOf(lastName)!=-1){ 
        			treeObj.selectNode(nodes[i]); 
        			//实现自动打开 
        			treeObj.expandNode(nodes[i], false,false , false); 
        			return false; 
        		} 
       		} 
        } 
       </script>
</head>
<body>
	<div>
		<div id="mmenu">
			<form action="" onsubmit="return doSearch();">
				<input type="text" id="search_str" value="" />
				<button type="submit" id="search">查找</button>
			</form>
			<div id="message">${message }</div>
		</div>
		<ul id="topicTree" class="ztree"></ul>
		<input type="hidden" id="changed" name="changed" />
	</div>
	
	<div id="addArea" style="display: none;">
	   <form action="" id="dictForm">
		<table style="border: 1px solid #cccccc;" class="inputTable">
		      <input type="hidden" name="id" id="dict_id"/>
		      <input type="hidden" name="parentId" id="dict_parentId"/>
		      <input type="hidden" name="objectId" id="dict_objectId"/>
		      <input type="hidden" name="sortId" id="dict_sortId"/>
		      <input type="hidden" name="type" id="dict_type"/>
              <tr>
                  <td class="label cancelBorderLeft">
                      <label for="dictionaryId">字典ID：</label>
                  </td>
                  <td class="content">
                      <input type="text" name="dictionaryId" id="dict_dictionaryId"/>
                  </td>
                  <td class="label">
                      <label for="name">字典名称：</label>
                  </td>
                  <td class="content">
                      <input type="text" name="name" id="dict_name"/>
                  </td>
              </tr>
              <tr>
                  <td class="label cancelBorderLeft">
                      <label for="value">字典值：</label>
                  </td>
                  <td class="content">
                      <input type="text" name="value" id="dict_value"/>
                  </td>
                  <td class="label cancelBorderLeft">
                      <label for="status">状态：</label>
                  </td>
                  <td class="content">
                     <select name="status" id="dict_status" value="1">
                          <option value="">请选择</option>
                          <jdf:select dictionaryId="111"/>
                      </select>
                  </td>
              </tr>
              <tr>
                  <td class="label cancelBorderLeft">
                      <label for="remark">备注：</label>
                  </td>
                  <td class="content" colspan="3">
                      <textarea rows="10" cols="65" name="remark" id="dict_remark"></textarea>
                  </td>
              </tr>
		     <tr>
				<td colspan="4" class="bottomLabel">
					<div class="right">
						<button type="button" onclick="saveDict()">保存</button>
					</div>
				</td>
			 </tr>
		  </table>
	  </form>
   </div>
	<script>
		var currentNode;
		var tree;
		var needSave; 
		var currentObjectId;
		function saveDict(){
			var name = $("#dict_name").val();
			var dictionaryId = $("#dict_dictionaryId").val();
			var value = $("#dict_value").val();
			var status = $("#dict_status").val();
			var remark = $("#dict_remark").val();
			var sortId = $("#dict_sortId").val();
			if(dictionaryId=='null'){
				dictionaryId = '';
			}
			if(isNull(name)){
				showMessage("名称不能为空");
				return;
			}
			if(!isInteger(value)){
				showMessage("字典值只能为整数");
				return;
			}
			/* if(isNull(status)){
				showMessage("状态不能为空");
                return;
			} */
			var params = $("#dictForm").serialize();
   			$.ajax({
				url:"<%=dynamicDomain%>/dict/treeSave?" + params + "&timstamp=" + (new Date()).valueOf(),
				type:'post',
				dataType:'json',
				success:function(msg){
					if(msg.result) {
						var dict = msg.entity;
						var zTree = $.fn.zTree.getZTreeObj("topicTree");
						//新增
						if(currentObjectId==""){
			                zTree.addNodes(currentNode, {"id":dict.objectId,"primaryKey":dict.id,"rel":"file","parentId":dict.parentId,"dictionaryId":dict.dictionaryId,
                                "name":msg.displayName,"status":dict.status,"sortId":dict.sortId,"remark":dict.remark,"type":dict.type,"realName":dict.name,"value":dict.value});
						}else{
							//修改
							currentNode.dictionaryId=dict.dictionaryId;
							currentNode.name=msg.displayName;
							currentNode.realName=dict.name;
							currentNode.primaryKey=dict.id;
							currentNode.status=dict.status;
							currentNode.remark=dict.remark;
							currentNode.value=dict.value;
							zTree.updateNode(currentNode);
						}
						showMessage("<jdf:message code="common.base.saveSuccess"/>",5000);
					} else {
						showMessage("<jdf:message code="common.base.fail"/>",5000);
				  	}
				  }
		     });
   			
   			 $("#addArea").dialog("close"); 
		}
	
		
		function saveOrder(){
		 	 var menu = $(tree).plugins.checkbox.get_checked();   
		    //得到节点的id，拼接成字符串   
		    var ids="";   
		    for(i=0;i<menu.size();i++){   
		        ids += menu[i].id+";";   
		    }   
		    alert(ids);   
		}
	</script>

</body>
</html>